package nu.zoom.catonine.tail;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.LinkedList;
import java.util.regex.Pattern;

public class TailerProfiling {

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		TailerProfiling app = new TailerProfiling();
		app.run(args);
	}

	private void run(final String[] args) throws Exception {
		final FullFileTailer tailer = new FullFileTailer(new MockPreferences());
		tailer.setBlockMatcherStarting(true);
		tailer.setLogBlockRegularExpression(Pattern.compile("... \\d?\\d, 2011"));
		tailer.setCharSet("utf-8");
		tailer.setReadBufferSize(64 * 1024);
		final File f = new File(args[0]);
		RandomAccessFile rf = new RandomAccessFile(f, "r");
		System.out.println("Reading file: " + f + " with size " + rf.length());

		tailer.setFile(f);
		final Listener l = new Listener();
		tailer.addListener(l);
		long starttime = System.currentTimeMillis();
		tailer.read();
		System.out.println("TIme: " + (System.currentTimeMillis() - starttime));
		System.out.println("Listener got: " + l.totalLines.size() + " entries");
	}

	static class Listener implements TailerListener {
		LinkedList<LogEntry> totalLines = new LinkedList<TailerListener.LogEntry>();
		boolean waitForLines = true;

		@Override
		public synchronized void lines(TailerLinesEvent lines) {
			LogEntry lastAddedEntry = this.totalLines.peekLast();
			for (LogEntry newLine : lines.entries) {
				if ((lastAddedEntry != null) && (lastAddedEntry.position == newLine.position)) {
					// Update of existing entry
					this.totalLines.removeLast();
				}

				this.totalLines.add(newLine);
				lastAddedEntry = newLine;
			}
			waitForLines = false;
			notifyAll();
		}

		public synchronized void setExpectingMoreLines() {
			waitForLines = true;
		}

		public synchronized void waitForLines() throws InterruptedException {
			while (waitForLines) {
				wait(100);
			}
		}

		@Override
		public void tailerWorking() {
		}

		public void tailerIdle() {
		}

		@Override
		public void tailerStopped() {
		}

		@Override
		public void tailerHasBeenReset() {
		}
	}

}
